import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:tot_android_flutter/base/BaseController.dart';
import 'package:tot_android_flutter/router/AppRoutes.dart';
import 'package:tot_android_flutter/utils/JsonUtil.dart';
import 'package:tot_android_flutter/utils/sp/Sp.dart';
import '../../common/widget/state/view_state.dart';
import '../../utils/ToastUtil.dart';
import '../../utils/log_util.dart';

class LoginController extends BaseController {
  final RxBool isChecked = false.obs; // 隐私协议是否同意
  final RxBool browseOn = true.obs; // 密码是否可见

  final TextEditingController nameTextController =
  TextEditingController(text: "GUOYH2021");

  final TextEditingController passwordTextController =
  TextEditingController(text: "GUOYH2021");

  FocusNode focusNameNode = FocusNode();
  FocusNode focusPwNode = FocusNode();
  RxBool hasNameFocus = false.obs;
  RxBool hasPwFocus = false.obs;

  RxBool nameIsEmpty = true.obs;
  @override
  void loadData() {
    viewState.value = ViewStateSuccess();
    focusNameNode.addListener((){
      hasNameFocus.value = focusNameNode.hasFocus;
    });

    focusPwNode.addListener((){
      hasPwFocus.value = focusPwNode.hasFocus;
    });
    nameTextController.addListener((){
      nameIsEmpty.value = nameTextController.text.isEmpty;
    });
  }

  @override
  void dispose() {
    super.dispose();
    focusNameNode.dispose();
    focusPwNode.dispose();
  }
  void login() {
    String userName = nameTextController.text.trim();
    String pw = passwordTextController.text.trim();
    if (userName.isEmpty) {
      ToastUtil.showToast("用户名为空");
      return;
    }
    if (pw.isEmpty) {
      ToastUtil.showToast("密码为空");
      return;
    }
    if (!isChecked.value) {
      ToastUtil.showToast("请先勾选");
      return;
    }

    sendRequest(apiService.login(userName, pw),
        bindViewState: false, showLoadingDialog: true, successCallback: (data) {
        ToastUtil.showToast("登录成功");
        Sp.putUserInfo(data);
        if (Get.previousRoute.isNotEmpty) {
          // 如果有页面，使用 Get.back()
          Get.back();
        } else {
          // 如果没有页面，使用 Get.offAll() 跳转到 index 页面
          Get.offAll(() => Get.toNamed(AppPages.INDEX));
        }

      WanLog.d("login success:${JsonUtils.toJson(data)}");
    });
    WanLog.d("userName:${userName},pw:${pw}");
  }
}
